


//
//  HMHomeTableViewController.m
//  黑马微博-wzy
//
//  Created by Mac on 2016/11/27.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "HMHomeTableViewController.h"
#import "HMTitleButton.h"
#import "HMPopMenu.h"
#import "HMAccountTool.h"
#import "HMStatus.h"
#import "HMUser.h"
#import "HMLoadMoreFooter.h"
//获取微博首页数据的工具类
#import "HMStatusTool.h"
//获取用户账号信息的工具类
#import "HMUserTool.h"
//自定义的cell
#import "HMStatusCell.h"
//
#import "HMStatusFrame.h"


@interface HMHomeTableViewController ()<HMPopMenuDelete>

//存放:获取的微博数据(字典)->模型->计算出的模型对应的frame
@property (nonatomic, strong) NSMutableArray *statusFrames;

@property (nonatomic, weak) UIRefreshControl *refreshControl;
@property (nonatomic, weak) HMLoadMoreFooter *footer;
@property (nonatomic, strong) HMTitleButton *titleButton;

@end

@implementation HMHomeTableViewController

- (NSMutableArray *)statusFrames{
    if (_statusFrames == nil) {
        _statusFrames = [NSMutableArray array];
    }
    return _statusFrames;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = HMColor(211, 211, 211);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //设置导航栏
    [self setupNavgiationBar];
    
    //继承刷新控件
    [self setupRefresh];
    
    //获取用户信息
    [self setupUserInfo];
    
    //加载最新数据
//    [self loadNewStatus];
}

#pragma mark - 获取用户信息
- (void)setupUserInfo{
    //1.封装的参数
    HMUserInfoParam *param = [[HMUserInfoParam alloc] init];
    param.uid = [HMAccountTool account].uid;
    
    //2.加载用户信息
    [HMUserTool userInfoWithParams:param success:^(HMUserInfoResult *result) {
        //成功
        HMUser *user = result;
        
        //设置用户昵称为nav 标题
        [self.titleButton setTitle:user.name forState:UIControlStateNormal];
        
        //存储账号信息
        HMAccount *account = [HMAccountTool account];
        account.name = user.name;
        [HMAccountTool save:account];
        
    } failure:^(NSError *error) {
        //失败
        [MBProgressHUD showError:@"获取数据失败!"];
        
        HMLog(@"%@", error);
    }];
        
}



//继承刷新控件
- (void)setupRefresh{

   //1/添加
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [self.tableView addSubview:refreshControl];
    self.refreshControl = refreshControl;
    
    //2/监听状态
    [refreshControl addTarget:self action:@selector(refreshControlStateChange:) forControlEvents:UIControlEventValueChanged];
    
    //3/刷新图标开始转动
    [refreshControl beginRefreshing];
    
    //4/加载数据
    //延迟
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
        [self refreshControlStateChange:refreshControl];
//    });
    
    //5/上拉加载更多控件
    HMLoadMoreFooter *footer = [[HMLoadMoreFooter alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    
    self.tableView.tableFooterView = footer;
    self.footer = footer;
    
}

//当下拉刷新控件进入刷新状态 (转圈圈)的时候会自动调用
- (void)refreshControlStateChange:(UIRefreshControl *)refreshControl{
    
    [self loadNewStatus:refreshControl];
}

//判断是否刷新
- (void)refresh:(BOOL)fromSelf{
    //当有新消息的时候再刷新
    if (self.tabBarItem.badgeValue) {
        //转圈圈
        [self.refreshControl beginRefreshing];
        
        NSIndexPath *firstRow = [NSIndexPath indexPathForRow:0 inSection:0];
        //UITableViewScrollPositionTop:滚到某一行的顶部
        [self.tableView scrollToRowAtIndexPath:firstRow atScrollPosition:UITableViewScrollPositionTop - 64 animated:YES];
        
        //刷新数据
        [self loadNewStatus:self.refreshControl];
    }else if(fromSelf){
        //没有新消息的时候
        //让表格回到最顶部
        NSIndexPath *firstRow = [NSIndexPath indexPathForRow:0 inSection:0];
        //UITableViewScrollPositionTop:滚到某一行的顶部
        [self.tableView scrollToRowAtIndexPath:firstRow atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    
}


#pragma mark - 提示用户新微博的数据数量
- (void)showNewStatusesCount:(NSInteger)count{
    //0.清零提醒数字
    [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - self.tabBarItem.badgeValue.intValue;
    self.tabBarItem.badgeValue = nil;
    
   // 1/创建一个label
    UILabel *countLabel = [[UILabel alloc] init];
    //2/设置文字
    if (count) {
        countLabel.text = [NSString stringWithFormat:@"共有%ld条新的微博数据", count];
    }else{
        countLabel.text = @"没有最新的微博数据";
    }
    countLabel.textAlignment = NSTextAlignmentCenter;
    countLabel.textColor = [UIColor whiteColor];
    
    //3/设置背景
    countLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    //4/设置frame
    countLabel.width = self.view.width;
    countLabel.height = 50;
    countLabel.x = 0;
    countLabel.y = 64 - countLabel.height;
    //5/添加到导航栏
    [self.navigationController.view insertSubview:countLabel belowSubview:self.navigationController.navigationBar];
    //6/动画
    CGFloat duration = 1.0;
    countLabel.alpha = 0.0;
    
    [UIView animateWithDuration:duration animations:^{
        //往下移动一个 countLabel.height
        countLabel.transform = CGAffineTransformMakeTranslation(0, countLabel.height);
        countLabel.alpha = 1.0;
    } completion:^(BOOL finished) {
        //向下移动完毕后调用的方法
        //延迟delay 后再执行
        CGFloat delay = 1.0;
        [UIView animateWithDuration:duration delay:delay options:UIViewAnimationOptionCurveEaseInOut animations:^{
            /*
             UIViewAnimationOptionCurveEaseInOut  = 0 << 16, // default//开始:由慢到快; 结束:由快到慢
             UIViewAnimationOptionCurveEaseIn     = 1 << 16,//由慢到快
             UIViewAnimationOptionCurveEaseOut    = 2 << 16,//由快到慢
             UIViewAnimationOptionCurveLinear     = 3 << 16,//线性,匀速
             */
            //回到初始位置
            countLabel.transform = CGAffineTransformIdentity;
            //透明度
            countLabel.alpha = 0.0;
            
        } completion:^(BOOL finished) {
            //删除控件
            [countLabel removeFromSuperview];
            
        }];
        
    }];
    
    
}

#pragma mark - 设置导航栏
- (void)setupNavgiationBar{

    //添加导航按钮 左边
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" hightImageName:@"navigationbar_friendsearch_highlighted" target:(id)self action:@selector(friendSearch)];
    
    //设置导航栏按钮 右边
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" hightImageName:@"navigationbar_pop_highlighted" target:(id)self action:@selector(pop)];
    
    //设置导航栏 中间 标题 按钮
    HMTitleButton *titleButton = [[HMTitleButton alloc] init];
//    titleButton.backgroundColor = [UIColor yellowColor];
    titleButton.height = 35;
   //titleButton.width 在 HMTitleButton 里面重写过了
    //文字
    NSString *title = [HMAccountTool account].name;
    
    //如果title 存在,就使用title,如果title 不存在,就使用 @"首页"
    [titleButton setTitle:title ? title: @"首页" forState:UIControlStateNormal];
    
    //图片
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    //????? 缺少 该图片
    [titleButton setBackgroundImage:[UIImage resizedImage:@"navigationbar_filter_background_highlighted"] forState:UIControlStateHighlighted];
    [titleButton addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleButton;

    self.titleButton = titleButton;
    
}

//加载最新的微博数据
- (void)loadNewStatus:(UIRefreshControl *)refreshControl{
    //1.封装参数
    HMHomeStatusesParam *param = [[HMHomeStatusesParam alloc] init];
    //获取数组中的第一个元素
    HMStatusFrame *firstStatusFram = [self.statusFrames firstObject];
    HMStatus *firstStatus = firstStatusFram.status;
    //如果firstStatus 存在
    //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    if (firstStatus) {
        param.since_id = @([firstStatus.idstr longLongValue]);
    }

    //2.加载微博数据
    [HMStatusTool homeStatusWithParams:param success:^(HMHomeStatusesResult *result) {
        //停止转圈圈
        [refreshControl endRefreshing];
        //成功
        //获取最新的微博frame数组
        NSArray *newFrames = [self statusFramesWithStatuses:result.statuses];
        
        //将新数据插入到原有数据的最前面
        NSRange range = NSMakeRange(0, [newFrames count]);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        
//        HMLog(@"self.statusFrames == %@", self.statusFrames);
        
        [self.statusFrames insertObjects:newFrames atIndexes:indexSet];
        
        [self.tableView reloadData];
        
        //让刷新控件停止刷新(恢复默认的状态)
        [refreshControl endRefreshing];
        //提示用户最新的微博数量
        [self showNewStatusesCount:[newFrames count]];
        
    } failure:^(NSError *error) {
        
        [refreshControl endRefreshing];
        //失败
        HMLog(@"%@", error);
    }];


}


//加载更多的微博数据
- (void)loadMoreStatus{

    //1.封装请求参数
    HMHomeStatusesParam *param = [HMHomeStatusesParam param];
    HMStatusFrame *lastStatusFrame = [self.statusFrames lastObject];
    HMStatus *lastStatus = lastStatusFrame.status;
    if (lastStatus) {
        param.max_id = @([lastStatus.idstr longLongValue] - 1);
    }
    
    //2.加载微博数据
    [HMStatusTool homeStatusWithParams:param success:^(HMHomeStatusesResult *result) {
        //获取最新的微博frame数组
        NSArray *newframes = [self statusFramesWithStatuses:result.statuses];
        //将新的数据添加到原有数据后面
        [self.statusFrames addObjectsFromArray:newframes];
        
        
//        HMLog(@"self.statusFrames **** %@", self.statusFrames);
        
        //刷表
        [self.tableView reloadData];
        
        //让刷新控件停止刷新
        [self.footer endRefreshing];
        
    } failure:^(NSError *error) {
        //
        HMLog(@"请求失败---- %@", error);
        //让刷新控件停止刷新
        [self.footer endRefreshing];
    }];

}

#pragma mark ====== 弹出菜单协议 =======
- (void)popMenuDidDismissed:(HMPopMenu *)popMenu{
    HMTitleButton *titleButton = (HMTitleButton *)self.navigationItem.titleView;
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];

}

- (void)titleButtonClick:(UIButton *)button{
//    button.selected = !button.selected;
//
//    if (button.selected) {
        [button setImage:[UIImage imageWithName:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
//    }else{
//    
//        [button setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
//    }
    //弹出菜单
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd];
    btn.backgroundColor = [UIColor blueColor];
    
    
    HMPopMenu *popMenu = [[HMPopMenu alloc] initWithContentView:nil];
    popMenu.deletegate = self;
    popMenu.dimBackground = YES;
    [popMenu showInRect:CGRectMake(100, 0, 200, 480)];

}


//导航栏 左边 扫码
- (void)friendSearch{

    HMLog(@"friendSearch===");
}

//导航栏 右边 添加
- (void)pop{

    HMLog(@"pop-------");

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //当没有数据的时候,脚视图上"上拉加载更多"的提示隐藏
    self.tableView.tableFooterView.hidden = self.statusFrames.count == 0;
        
    return self.statusFrames.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    HMStatusCell *cell = [HMStatusCell cellWithTableView:tableView];
    
    cell.statusFrame = self.statusFrames[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    HMStatusFrame *frame = self.statusFrames[indexPath.row];
    
    return frame.cellHeight;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{



}

#pragma mark - UITableView继承自UIScrollView,所以UIScrollView里面的代理方法对UITableView也同样适用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.statusFrames.count <= 0 || self.footer.isRefreshing)  return;
    //1.差距
    CGFloat delta = scrollView.contentSize.height - scrollView.contentOffset.y;
    
    //刚好能看到完整的footer的高度
    CGFloat sawFooterH = self.view.frame.size.height - self.tabBarController.tabBar.frame.size.height;
    
//    HMLog(@"delta:%f === sawFooterH:%f", delta, sawFooterH);
    
    //2.如果能看见整个footer
    if (delta <= (sawFooterH - 0)) {
        //进入上拉刷新状态
        [self.footer beginRefreshing];
        
        //加载更多的数据
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //
            [self loadMoreStatus];
        });
    }
    
}


#pragma mark - 将 微博模型 转化为 微博frame 模型
- (NSArray *)statusFramesWithStatuses:(NSArray *)statuses{
    NSMutableArray *frames = [NSMutableArray array];
    for (HMStatus *status in statuses) {
        //传递微博模型数据,计算所有子控件的frame
        HMStatusFrame *frame = [[HMStatusFrame alloc] init];
        frame.status = status;
        [frames addObject:frame];
    }
    return frames;
}

@end
